package jvlite.dao.JliteORM;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

// the skeleton does not force the user to mapping the result set to a existed object
// while left the authority to  user just like spring framework
// instead of that, the skeleton offer several useful method to deal with result set
public class BeanHandler implements IResultSetHandler {

 private Class<?> clazz;

 public BeanHandler(Class<?> clazz) {
     this.clazz = clazz;
 }

 @Override
 public Object handler(ResultSet rs) {

     try {
         if (!rs.next()) {
             return null;
         }
         // create the data bean to encapsulate the result set
         Object bean = clazz.newInstance();

         // obtain the meta data
         ResultSetMetaData meta = rs.getMetaData();
         int count = meta.getColumnCount();
         for (int i = 0; i < count; i++) {
        	 // get the name and id of each field
             String name = meta.getColumnName(i+1);
             Object value = rs.getObject(name);     // 1

             // use reflect to get the properties of class which mapping the field of table 
             Field f = bean.getClass().getDeclaredField(name);
             f.setAccessible(true);
             f.set(bean, value);
         }
         return bean;
     } catch (Exception e) {
         throw new RuntimeException(e);
     }
 }

}